<?php


// no direct access
defined('_JEXEC') or die();

jimport('joomla.application.component.model');

class SimplelistingModelFields extends JModel
{
	
	var $_currentTableName = '' ;	
	var $_lastId = 0;
        var $_data = null;
	var $_total = null;
	var $_pagination = null;
	var $_table_prefix = null;


        function __construct()
	{
		parent::__construct();

//		global $mainframe, $context;
                $this->_table_prefix = '#__simplelisting';

//		$limit	= $mainframe->getUserStateFromRequest( $context.'limit', 'limit', $mainframe->getCfg('list_limit'), 0);
//		$limitstart = $mainframe->getUserStateFromRequest( $context.'limitstart', 'limitstart', 0 );

                $application= JFactory::getApplication();
                $option = JRequest::getCmd( 'option').'-fields';

		$limit	= $application->getUserStateFromRequest( 'global.list.limit', 'limit', $application->getCfg('list_limit'), 'int');
		$limitstart = $application->getUserStateFromRequest( $option.'limitstart', 'limitstart', 0, 'int' );

		$this->setState('limit', $limit);
		$this->setState('limitstart', $limitstart);
	}

        function getData()
	{
            if (empty($this->_data))
            {
                $query = $this->_buildQuery();
                $this->_data = $this->_getList($query, $this->getState('limitstart'), $this->getState('limit'));
            }
		return $this->_data;
        }


	function getTotal() {

            if (empty($this->_total)) {
                $query = $this->_buildQuery();
                $this->_total = $this->_getListCount($query);
            }

            return $this->_total;
	}


	function getPagination()
	{
		// Lets load the content if it doesn't already exist
		if (empty($this->_pagination))
		{
			jimport('joomla.html.pagination');
			$this->_pagination = new JPagination( $this->getTotal(), $this->getState('limitstart'), $this->getState('limit') );
		}

		return $this->_pagination;
	}



    function _buildQuery()
    {
        $where = $this->_buildContentWhere();
        $orderby = $this->_buildContentOrderBy();

        $query = 'SELECT f.*'.
        ' FROM '. $this->getSqlTableName() . ' as f'.
        $where
        .$orderby;
        return $query;
    }

    function _buildContentWhere()
    {
                global $mainframe, $option;
                $db                 =& JFactory::getDBO();
                $where = array();


                if ($search) {
                    $where[] = 'LOWER(f.name) LIKE '.$db->Quote('%'.$db->getEscaped( $search, true ).'%', false );
                }

                 $where = ( count( $where ) ? ' WHERE '. implode( ' AND ',$where ) : '' );
                 return $where;
    }

    function _buildContentOrderBy()
    {
        $application= JFactory::getApplication();
        $option = JRequest::getCmd( 'option').'-fields';

        $filter_order     = $application->getUserStateFromRequest( $option.'filter_order', 'filter_order', 'f.ordering', 'cmd' );
        $filter_order_Dir = $application->getUserStateFromRequest( $option.'filter_order_Dir',  'filter_order_Dir', '', 'word' );

        if ($filter_order == 'f.ordering'){
                $orderby 	= ' ORDER BY f.ordering '.$filter_order_Dir;
        } else {
                $orderby 	= ' ORDER BY '.$filter_order.' '.$filter_order_Dir.' , f.ordering ';
        }

        return $orderby;
//        global $mainframe, $option;
//        if ($filter_order == 'ordering'){
//                $orderby 	= ' ORDER BY f.ordering ';
//        } else {
//       $orderby = ' ORDER BY  f.ordering ASC';
//        }
//        return $orderby;
    }




        /* ID Functions */
        function getId()
	{
		//First loooking for new insertion
		if ($this->_lastId > 0) {
			return $this->_lastId ;
		}

		$cid = $this->getCid();

		if (empty($cid[0])) {
			//try to see id
			return JRequest::getInt('id', 0);
		}

		return $cid[0] ;
	}

	function getCid()
	{
		$cid = JRequest::getVar( 'cid', array(0), '', 'array' );
		JArrayHelper::toInteger( $cid, array(0) );

		return $cid ;
	}

	function &getRow()
	{
		$table =& $this->getTable();
		$table->load( $this->getId() );

		return $table;
	}

/* Edit functions */

	function save()
	{
		$row = & $this->getRow();
		
		$row->name = JRequest::getVar( 'name', '' ) ;
		
		
            if( !$row->id ){
                    // save new item at the end of ordering
                    $row->ordering = $row->getNextOrder();
		}

        if ( !$row->store() ) {
            JError::raiseWarning( 200, $row->getError() );
            return false;
        }
        
        $this->_lastId = $row->id;
        return true;
		
	}
	
	function remove()
	{
		$cids = implode( ',', $this->getCid() );
		
		//only one request
		$this->_db->setQuery( 'DELETE FROM `'. $this->getSqlTableName() .'` WHERE id IN (' . $cids . ')' );
		
		if ( !$this->_db->query() ) {
			JError::raiseError( 500, $this->_db->getErrorMsg() );
			return false;
		}
		
		return true;
	}



/* Sort out tables */

        function &getTable()
	{
		static $tables = array();

		$tableName = $this->getTableName() ;

		if (!isset($tables[$tableName])) {
			$tables[$tableName] =& parent::getTable( ucfirst( $tableName ) );
		}

		return $tables[$tableName]  ;
	}

	function getSqlTableName()
	{
		$table =& $this->getTable();
	    return $table->getTableName();
	}


	function setTableName( $tableName )
	{
		$tables = array(
                'categories',
		'types',
                'extras',
                'layouts',
                'facilities',
                'countries'
			);

		if( !in_array( $tableName, $tables ) ){

			    JError::raiseWarning( 200, 'table name : ' . $tableName . 'doesn\'t exists' );
				return false;
		}

		$this->_currentTableName =  $tableName ;


		return $this->_currentTableName ;
	}


        function getTableName()
        {
                if ( empty($this->_currentTableName) ) {

                        $mainframe = &JFactory::getApplication();
                        $tableName = $mainframe->getUserStateFromRequest( 'com_simplelisting.field', 'table', 'types', 'word' );
                        $this->setTableName( $tableName );
                }

                return $this->_currentTableName ;
        }

        function publish($cid = array(), $publish=1)
        {
            if (count( $cid ))
            {
            $cids = implode( ',', $cid );

            $query = 'UPDATE '. $this->getSqlTableName() .
                     ' SET published = ' . intval( $publish )
                    . ' WHERE id IN ( '.$cids.' )'
            ;
            $db = $this->getDBO();
            $db->setQuery($query);
                if (!$db->query()){
                        $errorMessage = $this->getDBO()->getErrorMsg();
                        JError::raiseError(500,  JText::_('ERROR_UPDATING_MSG').$errorMessage);
                }
            }
        }

}
